<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
		<title>后台-修改文章</title>
		<link rel="shortcut icon" th:href="@{/image/favicon.ico}" type="image/x-icon"/>
		<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
		<link th:href="@{/css/materialdesignicons.min.css}" rel="stylesheet">
		<link th:href="@{/css/style.min.css}" rel="stylesheet">
		<!-- 引入 css -->
		<link th:href="@{/wangEditor/style.css}" rel="stylesheet" type="text/css">
		<!--标签插件-->
		<link rel="stylesheet" th:href="@{/js/jquery-tags-input/jquery.tagsinput.min.css}">
		<style type="text/css">
			#editor-wrapper {
				z-index: 100;
				border: 1px solid #0FB25F;
			}
		</style>
	</head>
	<body>
		<div class="lyear-layout-web">
			<div class="lyear-layout-container">
				<div th:replace="comm/WL2022-CommAdmin :: #commLeftNavigation"></div>
				<div th:replace="comm/WL2022-CommAdmin :: #commHeader"></div>

				<!--页面主要内容-->
				<main class="lyear-layout-content">

					<div class="container-fluid">

						<div class="row">
							<div class="col-lg-12">
								<div class="card">
									<div class="card-body">

										<form action="#!" method="post" class="row">
											<div class="form-group col-md-12">
												<label for="title">标题</label>
												<input type="text" name="title" id="title" class="form-control" th:value="${editArticle.title}"
													maxlength="15" placeholder="博客标题（不可修改）" disabled="">
											</div>
											<div class="form-group col-md-12">
												<label for="createBy">作者</label>
												<input type="text" name="createBy" class="form-control" id="createBy"
													th:value="${editArticle.createBy}" maxlength="10" placeholder="作者">
											</div>

											<div class="form-group col-md-12">
												<label for="summary">博客描述</label>
												<textarea id="summary" class="form-control" name="summary"
													maxlength="200" th:text="${editArticle.summary}" placeholder="博客描述..." rows="5"
													style="resize: none"></textarea>
											</div>
											<div class="form-group col-md-12">
												<label for="headImage">文章头图片</label>
												<div class="form-controls">
													<ul class="list-inline clearfix lyear-uploads-pic">
														<li class="col-xs-4 col-sm-3 col-md-2">
															<img th:src="@{/image/articleImages/{imageName}(imageName=${editArticle.image})}" th:alt="${editArticle.image}" id="image">
														</li>
														<li class="col-xs-4 col-sm-3 col-md-2">
															<a class="pic-add" id="add-pic-btn" title="点击上传"
																onclick="addImage()"></a>
															<input type="file" name="headImage" id="headImage"
																onchange="addHeadImage(this)" style="display: none;">
														</li>
													</ul>
												</div>
											</div>
											<div class="form-group col-md-12">
												<label for="articleType">类型</label>
												<div class="form-controls">
													<select name="articleType" class="form-control" id="articleType">
														<option th:each="byType:${categoryNavigation}" th:value="${byType.id}" th:selected="${editArticle.articleType}==${byType.id}">[[${byType.articleType}]]</option>
													</select>
												</div>
											</div>

											<div class="form-group col-md-12" id="quoteLink">
												<label>状态</label>
												<div>
													<label class="lyear-radio radio-inline radio-primary">
														<input type="radio" name="quoteLink" value="me"
															onchange="t1(this)" th:checked="${editArticle.quoteLink}==''"><span>原创</span>
													</label>
													<label class="lyear-radio radio-inline radio-primary">
														<input type="radio" name="quoteLink" value="notMe"
															onchange="t2(this)" th:checked="${editArticle.quoteLink}!=''" ><span>转载</span>
													</label>
													<input id="quoteLinkText" name="quoteLinkText" type="text"
														placeholder="请输入引用链接"
														th:value="${editArticle.quoteLink}"
														th:style="${editArticle.quoteLink}!=''?'height: 30px;width: 250px;display: inline':'height: 30px;width: 250px;display: none'"
														class="form-control" />
												</div>
											</div>

											<div class="form-group col-md-12">
												<label for="editor-content-textarea">文章内容(内容过多建议打开全屏修改)</label>
												<div class="page-right" style="display: flex;">
													<!-- 编辑器 DOM -->
													<div style="border: 1px solid #ccc; flex: 1" id="editor-wrapper">
														<div id="editor-toolbar" style="border-bottom: 1px solid #ccc;">
														</div>
														<div id="editor-text-area" style="height: 350px"></div>
														<textarea id="editor-content-textarea" style="display: none"
															name="articleContent" readonly></textarea>
													</div>
													<!-- 标题目录 -->
													<div style="width: 200px; background-color: #f1f1f1;">
														<ul id="header-container"></ul>
													</div>
												</div>
											</div>
											<div class="form-group col-md-12">
												<button class="btn btn-primary" lay-submit lay-filter="submitMy">保存修改</button>
												<button type="button" class="btn btn-default"
													onclick="javascript:history.back(-1);return false;">返 回</button>
											</div>
										</form>
									</div>
								</div>
							</div>

						</div>

					</div>

				</main>
				<!--End 页面主要内容-->
			</div>
		</div>

		<script th:src="@{/layui/layui.js}"></script>
		<script type="text/javascript" th:src="@{/js/jquery-3.6.0.min.js}"></script>
		<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
		<script type="text/javascript" th:src="@{/js/perfect-scrollbar.min.js}"></script>
		<script type="text/javascript" th:src="@{/js/main.min.js}"></script>
		<!--标签插件-->
		<script th:src="@{/js/jquery-tags-input/jquery.tagsinput.min.js}"></script>
		<!-- 引入 js -->
		<script th:src="@{/wangEditor/index.js}"></script>
		<!-- 引入 js -->
		<script th:src="@{/wangEditor/index.js}"></script>
		<script type="text/javascript">
			function addImage() {
				$("#headImage").click();
			}
			//选择文件完毕的回调
			function addHeadImage(obj) {
				const file = obj.files[0];
				console.log(file);
				const reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = function() {
					$("#image").attr("src", this.result);
				}
			}
		</script>
		<!--控制引用链接输入框-->
		<script type="text/javascript">
			function t1(obj) {
				let val = $("input[name='quoteLink']:checked").val();
				if (val === "me") {
					$("#quoteLinkText").css('display', 'none');
				}
			}

			function t2(obj) {
				let val = $("input[name='quoteLink']:checked").val();
				if (val === "notMe") {
					$("#quoteLinkText").css('display', 'inline');
				}
			}
		</script>
		<!-- WangEdit的设置 -->
		<script>
			const E = window.wangEditor
			// 标题 DOM 容器
			const headerContainer = document.getElementById('header-container')
			headerContainer.addEventListener('mousedown', event => {
				if (event.target.tagName !== 'LI') return
				event.preventDefault()
				const id = event.target.id
				editor.scrollToElem(id) // 滚动到标题
			})
			//文章内容的设置
			const html = unescapeHTML("[[${editArticle.articleContent}]]");
			window.editor = E.createEditor({
				selector: '#editor-text-area',
				html:html,
				config: {
					placeholder: '请输入文章内容...',
					MENU_CONF: {
						uploadImage: {
							base64LimitSize: 10 * 1024 * 1024 // 10M 以下插入 base64
						}
					},
					onChange(editor) {
						document.getElementById('editor-content-textarea').value = editor.getHtml();
						const headers = editor.getElemsByTypePrefix('header')
						headerContainer.innerHTML = headers.map(header => {
							const text = E.SlateNode.string(header)
							const {
								id,
								type
							} = header
							return `<li id="${id}" type="${type}">${text}</li>`
						}).join('')
					}
				}
			})
			window.toolbar = E.createToolbar({
				editor,
				selector: '#editor-toolbar',
				config: {}
			})
			function unescapeHTML(text) {
				//1.首先动态创建一个容器标签元素，如DIV
				let temp = document.createElement("divs");
				//2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
				temp.innerHTML = text;
				//3.最后返回这个元素的innerText(ie支持)或者textContent(火狐，google支持)，即得到经过HTML解码的字符串了。
				const output = temp.innerText || temp.textContent;
				temp = null;
				return output;
			}
		</script>

		<script>
			//保存文章修改的异步提交
			layui.use(['jquery', 'form',], function () {
				const layer = layui.layer;
				const form = layui.form;
				const $ = layui.jquery;
				form.on('submit(submitMy)', function () {
					//1、先做内容是否为空的判断
					let createBy = $("#createBy").val();
					let summary = $("#summary").val();
					let articleType = $("#articleType").val();
					let quoteLinkText = $("#quoteLinkText").val();
					let editorContentTextarea = $("#editor-content-textarea").val();
					if(createBy.replace(/\s*/g, "")===''){
						layer.msg('作者不能为空！', {icon: 5});
						return false;
					}
					if(summary.replace(/\s*/g, "")===''){
						layer.msg('文章概述不能为空！', {icon: 5});
						return false;
					}
					if(editorContentTextarea === '<p><br></p>'){
						layer.msg('文章内容不能为空！', {icon: 5});
						return false;
					}
					//2、判断是否修改
					let oldCreateBy = '[[${editArticle.createBy}]]';
					let oldSummary = '[[${editArticle.summary}]]';
					let oldArticleType = '[[${editArticle.articleType}]]';
					let oldQuoteLink = "[[${editArticle.quoteLink}]]";
					let headImage = $("#headImage").get(0).files[0];
					//2.1、如果（全部旧的和新的相等)&&（headImage===undefined）则修改失败
					if((createBy===oldCreateBy)&&(summary===oldSummary)&&(articleType===oldArticleType)&&(quoteLinkText===oldQuoteLink)&&(headImage===undefined)&&(editorContentTextarea=== "[[${editArticle.articleContent}]]")){
						layer.msg('请修改后再提交！', {icon: 5});
					}
					//headImage文件的undefined判断决定url和formData
					let url="[[@{/root/modifyArticlesWithImag}]]";
					const formData = new FormData(); // 要提交的内容封装进formData
					formData.append("id",'[[${editArticle.id}]]');
					formData.append("createBy",createBy);
					formData.append("summary",summary);
					formData.append("articleType",articleType);
					formData.append("quoteLinkText",quoteLinkText);
					formData.append("editorContentTextarea",editorContentTextarea);
					if(headImage===undefined){
						//未修改图片
						url="[[@{/root/modifyArticles}]]"
					}else{
						if (!/image\/\w+/.test(headImage.type)) { //判断文件的是不是图片
							layer.msg('选择的图片格式不对,请重新上传...！', {icon: 5});
							return false;
						}
						formData.append("headImage", headImage);
					}
					$.ajax({
						url: url,
						type: "post",
						data: formData,
						cache: false,//上传文件无需缓存
						processData: false,//用于对data参数进行序列化处理 这里必须false
						contentType: false, //必须*/
						success: function (r) {
							if (r) {
								//弹出loading
								const index = top.layer.msg('修改成功！，稍后将跳转到后台首页', {icon: 16, time: false, shade: 0.8});
								setTimeout(function(){
									top.layer.close(index);
									//跳转到后台首页
									document.location.href = '[[@{/root/index}]]';
									return true;
								},3000);
							}else {
								layer.open({
									title: '修改失败',
									content: '麻烦联系一下管理员，连夜改bug',
									icon: 5
								});
							}
						},
						error: function () {
							layer.open({
								title: '程序出错',
								content: '程序故障！麻烦联系一下管理员',
								icon: 5
							});
						}
					})
					return false;
				})
			})
		</script>
	</body>
</html>
